import { EnvironmentContext } from "./cyberspace/environment";
import { coreConfig } from "../config";
import { promises as fs } from "fs";

const ActionDictionary: Record<
    string,
    (context: EnvironmentContext, args: string[]) => Promise<string> | string | void
> = {
    help: () => {
        return `
        帮助列表:
        help - 查看帮助列表
        exit - 退出程序
        ls - 列出当前目录下的文件
        cd - 切换工作目录
        `;
    },
    exit: (context) => {
        context.exit();
    },
    ls: async (context) => {
        const rootPath = context.rootPath;
        try {
            const files = await fs.readdir(rootPath, { withFileTypes: true });

            const formattedFiles = files.map((dirent) => {
                return dirent.isDirectory() ? `${dirent.name}/` : dirent.name;
            });

            return formattedFiles.join("\n");
        } catch (error) {
            return `路径不存在: ${rootPath}`;
        }
    },
    cd: (context, args) => {
        const targetPath = args[0];
        return context.changeDirectory(targetPath);
    }
};

export function getAction(actionKey: string) {
    const action = ActionDictionary[actionKey];
    if (!action) {
        return;
    }
    return action;
}
